import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
import ElementUI, { Notification } from 'element-ui';
import './assets/styles/element-variables.scss'
Vue.use(ElementUI);
Vue.prototype.$axios = axios
Vue.config.productionTip = false
window.captchaUrl = 'https://youpin.ink/canteen-admin/captcha'
window.uploadUrl = 'https://youpin.ink'
window.webSocketUrl = 'wss://youpin.ink/webSocket'
// window.captchaUrl = 'http://127.0.0.1:8080/canteen-admin/captcha'
// window.uploadUrl = 'http://127.0.0.1:8080'
// window.webSocketUrl = 'ws://127.0.0.1:58080/webSocket'
import './assets/styles/reset.css'
axios.defaults.baseURL = '/canteen-admin'
axios.defaults.timeout = 8000
axios.defaults.withCredentials = true
axios.interceptors.response.use(response => {
  switch (response.data.code) {
    case 200:
      if (response.data.msg) {
        Notification.success({
          title: '成功',
          message: response.data.msg
        })
      }
      return response.data
    case 500:
      if (response.data.msg) {
        Notification.error({
          title: '错误',
          message: response.data.msg
        })
      }
      return Promise.reject(response)
  }

}, error => {
  switch (error.response.status) {
    case 401:
      if (router.currentRoute.path !== '/login') {
        router.replace('/login')
        store.commit('clearState')
      }
      Notification.error({
        title: '错误',
        message: error.response.data.msg
      })
      return Promise.reject(error)
    case 403:
      Notification.error({
        title: '错误',
        message: error.response.data.msg
      })
      return Promise.reject(error)
  }
})

router.beforeEach((to, from , next) => {
  if (to.path === '/login') {
    next();
    return;
  }
  initPageHeader(to)
  initSocket()
  if (store.state.menus.length > 0 && store.state.adminInfo) {
    next();
    return;
  } else {
    initMenu()
    initAdminInfo()
  }
  next();
})

function initSocket () {
  // 建立socket连接
  if (window.WebSocket) {
    let socket = new WebSocket(window.webSocketUrl);
    // 相当于channel的read事件，ev 收到服务器回送的消息
    socket.onmessage = function (ev) {
      Notification.info({
        title: '提醒',
        message: ev.data
      })
    }
    socket.onopen = function () {
      console.log("连接开启")
    }
    // 相当于连接关闭
    socket.onclose = function () {
      console.log("连接关闭")
    }
  } else {
    console.log("当前浏览器不支持webSocket");
  }
}

function initAdminInfo () {
  axios.get('/auth/info').then(res => {
    if (res.code === 200) {
      store.commit('initAdminInfo', res.data)
    }
  })
}

function initMenu () {
  axios.get('/auth/menu').then(res => {
    if (res.code === 200) {
      store.commit('initMenu', res.data)
    }
  })
}

function initPageHeader(to) {
  store.commit('initPageHeader', to)
}

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
